package jsu.yym.tiktok.controller;

import jsu.yym.tiktok.mapper.FileMapper;
import jsu.yym.tiktok.mapper.Type;
import jsu.yym.tiktok.mapper.VideoMapper;
import jsu.yym.tiktok.pojo.File;
import jsu.yym.tiktok.pojo.RegisterUser;
import jsu.yym.tiktok.pojo.ResponseResult;
import jsu.yym.tiktok.pojo.User;
import jsu.yym.tiktok.mapper.UserMapper;
import jsu.yym.tiktok.server.*;
import jsu.yym.tiktok.service.LoginServiceImp;
import jsu.yym.tiktok.service.UserDataService;
import jsu.yym.tiktok.service.UserService;
import jsu.yym.tiktok.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

@RestController
@CrossOrigin
public class helloController {
    @Autowired
    private LoginServiceImp loginService;
    @Autowired
    private UserMapper userMapper;

    @Resource
    private idUtil util;

    @Resource
    private MD5Get md5Get;
    @Resource
    private mail m;
    @Resource
    RedisCache redisCache;
    @Resource
    UserDataService userDataService;
    @Autowired
    private FileMapper fileMapper;
    @Resource
    private VideoService videoService;
    @Resource
    private UserService userService;

    @GetMapping("/")
    public String hello(){
        System.out.println("hh");
//        videoService.test();
        userService.test();
        return "hello,Spring!";
    }


    //用户登录接口
    @PostMapping("/user/login")
    public ResponseResult loginUser(@RequestBody User user) throws Exception {
//        System.out.println("jj");
//        System.out.println(user.toString());
        //对user的密码进行加密
        user.setPassword(md5Get.getMD5(user.getPassword()));
        //认证授权
        ResponseResult responseResult =  loginService.login(user);
//        System.out.println(responseResult.toString());
        //分析用户之前所有的浏览记录，更新用户的标签
        String Label = userDataService.AnalyzeData(user.getUsername());
        int state = userMapper.getUserByUserName(user.getUsername()).getState();
        responseResult.setCode(state);
        System.out.println("aaa"+responseResult.toString());
        if (Label.isEmpty()) {
            //如果用户没有浏览记录，暂无标签
            return responseResult;
        }
        int count = userMapper.updateTargeByUsername(Label,user.getUsername());
        if(count<=0)
            return new ResponseResult(503,"更新标签失败");
        return responseResult;
    }


    //用户注册接口
    @PostMapping("/user/register")
    public ResponseResult registerUser(@RequestBody RegisterUser registerUser) throws Exception {
        //从redis中获取验证码
        String redisKey = "sendEmail:" + registerUser.getEmail();
        String code = redisCache.getCacheObject(redisKey);
        //判断验证码是否相同
        if(!code.equals(registerUser.getCode()))
            return new ResponseResult(400,"验证码错误");
        //生成id
        String id = util.creatID();
        String pwd = md5Get.getMD5(registerUser.getPassword());
        //封装到User对象中
        User user = new User(id,pwd,registerUser.getEmail());
        user.setState(2);
        user.setImage(Type.IMAGE);//设置默认头像
        user.setFileName(Type.FILE_NAME);
        user.setNickname(id);
        user.setSignature(Type.TT);
        user.setAddress(Type.TT);
        user.setSex("女");
        //存入数据库
        int count = userMapper.insert(user);
        if (count<=0)
            return new ResponseResult(503,"邮箱重复");
        //发送邮件，把生成的id发送给用户
        String text = "您好"+registerUser.getEmail()+"！欢迎使用SnapVid短视频应用，这是为您生成的账号，账号为："+id+"。请勿泄露！";
        String title = "SnapVid注册";
        m.sendMail(registerUser.getEmail(),text,title);
        //为用户创建一个默认收藏夹
        String s = "默认收藏夹";
        File file = new File(id,s);
        int count2 = fileMapper.insert(file);
        //添加到es中
        userService.savaUserToEs(user);
        if(count2<=0)
            return new ResponseResult(503,"初始化失败");
        return new ResponseResult(200,"注册成功");
    }

    //发送邮件获取验证码
    @PostMapping("/user/send/{email}")
    public ResponseResult sendEmailUser(@PathVariable String email)
    {
        System.out.println("hhh");
        //生成验证码，发送邮件
        String code = util.creatCode();
        String text = "您好"+email+"！欢迎使用SnapVid短视频应用，这是一封用于注册的邮件，验证码为："+code+"。如非本人操作请及时检查账号安全。";
        String title = "SnapVid注册验证";
        m.sendMail(email,text,title);

        //将验证码存入Redis
        //存到redis
        redisCache.setCacheObject("sendEmail:"+email,code);
        return new ResponseResult(200,"发送成功",code);
    }


    //找回密码
    @PostMapping("/user/recover")
    public ResponseResult recoverUser(@RequestBody RegisterUser registerUser) throws Exception {
        //从redis中获取验证码
        String redisKey = "forgetEmail:" + registerUser.getEmail();
        String code = redisCache.getCacheObject(redisKey);
        //判断验证码是否相同
        if(!code.equals(registerUser.getCode()))
            return new ResponseResult(400,"验证码错误");
        //将修改的密码存入数据库
        int count = userMapper.updateUserByEmail(md5Get.getMD5(registerUser.getPassword()),registerUser.getEmail());
        if(count<=0)
            return new ResponseResult(503,"失败");
        return new ResponseResult(200,"找回成功");
    }

    //找回密码发送验证码
    @PostMapping("/user/forget/{email}")
    public ResponseResult forgetUser(@PathVariable String email)
    {
        //生成验证码，发送邮件
        String code = util.creatCode();
        String text = "您好 3387503511@qq.com！欢迎使用SnapVid短视频应用，这是一封用于找回密码的邮件，验证码为："+code+"。如非本人操作请及时检查账号安全。";
        String title = "SnapVid找回密码";
        m.sendMail(email,text,title);

        //将验证码存入Redis
        //存到redis
        redisCache.setCacheObject("forgetEmail:"+email,code);
        return new ResponseResult(200,"发送成功",code);
    }
}
